import { defineStore } from "pinia";
import { UserState } from "@/stores/interface/userManagement";
import { getUserList } from "@/api/modules/userManagement";

export const userManagementStore = defineStore({
  id: "userManagement",
  state: (): UserState => ({
    tableData: [],
    pageInfo: { current: 1, pageSize: 10 },
    tableTotal: 0,
    searchForm: {},
    tableLoading: false,
    // 时间倒叙
    flashback: true,
    treeId: ""
  }),
  getters: {},
  actions: {
    async getTableData() {
      this.SET_TABLE_LOADING(true);
      const form = {
        ...this.searchForm,
        org_id: this.treeId,
        page_size: this.pageInfo.pageSize,
        page: this.pageInfo.current
      };
      const { data } = await getUserList(form);
      this.SET_TABLE_LOADING(false);
      this.SET_TABLE_DATA(data["results"]);
      this.SET_TABLE_TOTAL(data["count"]);
      // fetch
      //   ._getUserList(form)
      //   .then(({ data }) => {
      //     commit("SET_TABLE_LOADING", false);
      //     commit("SET_TABLE_DATA", data["results"]);
      //     commit("SET_TABLE_TOTAL", data["count"]);
      //   })
      //   .catch(error => {
      //     console.error(error);
      //     message.error("用户清单获取失败");
      //     commit("SET_TABLE_LOADING", false);
      //     commit("SET_TABLE_DATA", []);
      //     commit("SET_TABLE_TOTAL", 0);
      //   });
    },
    paginationChange(pagination) {
      this.PAGE_CHANGE(pagination);
      this.getTableData();
    },
    setFlashback(payload) {
      this.SET_FLASHBACK(payload);
    },
    SET_TABLE_DATA(payload) {
      this.tableData = payload;
    },
    SET_TABLE_TOTAL(payload) {
      this.tableTotal = payload;
    },
    PAGE_CHANGE(pagination) {
      if (this.pageInfo.pageSize !== pagination.pageSize) {
        this.pageInfo.current = 1;
        this.pageInfo.pageSize = pagination.pageSize;
      } else {
        this.pageInfo.current = pagination.current;
      }
    },
    SET_SEARCH_FORM(payload) {
      this.searchForm = {
        ...payload
      };
    },
    SET_TABLE_LOADING(payload) {
      this.tableLoading = payload;
    },
    SET_FLASHBACK(payload) {
      this.flashback = payload;
    },
    SET_SEARCH_TYPE_ID(payload) {
      this.treeId = payload;
    }
  }
});
